<template>
  <div class="pending-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="12">
        <div class="summary-item">
          项目合计金额：
          <span class="summary-value">{{ toDecimal2(Math.round(totalAmount * 100) / 100) }}</span>
          元
        </div>
<!--        <div class="summary-item">
          费率：
          <span class="summary-value">{{ rate }}</span>
          %
        </div>-->
        <el-button
          icon="el-icon-check"
          type="primary"
          :disabled="!hasSelected"
          @click="submit"
        >
          提交
        </el-button>
        <el-button
          icon="el-icon-download"
          type="success"
          :disabled="!hasSelected"
          @click="importFile"
        >
          导出
        </el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="12">
        <div class="summary-item summary-item-danger">
          被驳回：
          <span class="summary-value">{{ reject_count }}</span>
        </div>
        <el-form inline @submit.native.prevent>
          <el-form-item>
            <el-input
              v-model.trim="queryForm.keyword"
              placeholder="请输入供应商、收款人、手机号搜索"
              clearable
              class="search-input"
            />
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="search">
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table
      v-loading="listLoading"
      :data="list"
      @expand-change="handleExpandChange"
      class="table-box"
    >
      <el-table-column type="expand">
        <template #default="{ row, $index }">
          <el-table
            :data="row.children"
            class="subtable"
            border
            @selection-change="
              (selection) => handleSelectionChange($index, selection)
            "
          >
            <el-table-column
              type="selection"
              width="48"
              align="center"
              :selectable="isSelectable"
            />
            <el-table-column
              align="center"
              show-overflow-tooltip
              label="项目"
              prop="activity_name"
            />
            <el-table-column
              align="center"
              show-overflow-tooltip
              label="细项"
              prop="detail"
            />
            <el-table-column
              align="center"
              show-overflow-tooltip
              label="细项类别"
              prop="project_category"
            />
            <el-table-column
              align="center"
              show-overflow-tooltip
              label="数量"
              prop="number"
            />
            <el-table-column
              align="center"
              show-overflow-tooltip
              label="单价"
              prop="price"
            />
            <el-table-column
              align="center"
              show-overflow-tooltip
              label="小计"
              prop="subtotal"
            />
            <el-table-column
              align="center"
              show-overflow-tooltip
              label="项目时间"
              width="190"
            >
              <template #default="{ row: subRow }">
                <div v-if="subRow.activity_start_time">
                  {{ subRow.activity_start_time }}
                  ~
                  {{ subRow.activity_end_time }}
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" show-overflow-tooltip label="状态">
              <template #default="{ row: subRow }">
                <span
                  v-if="subRow.status === 4 || subRow.status === 5"
                  class="status-reject"
                  @click="showReason(subRow)"
                >
                  {{ subRow.status | detailStatus }}
                </span>
                <span v-else>{{ subRow.status | detailStatus }}</span>
                <span style="color: #f56c6c;font-size: 12px" v-if="subRow.is_supplier_check===2">（未认证）</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              show-overflow-tooltip
              label="操作"
              width="130"
            >
              <template #default="{ row: subRow }">
                <el-button
                  v-if="subRow.is_check == 1"
                  type="text"
                  class="sub-btn"
                  @click="showChecks(subRow)"
                >
                  查看验收材料
                </el-button>
                <el-button
                  v-else
                  type="text"
                  class="sub-btn sub-btn-danger"
                  @click="showUploadChecks(subRow.id, row)"
                >
                  上传验收材料
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        show-overflow-tooltip
        label="序号"
        type="index"
        width="95"
      />
      <el-table-column align="center" show-overflow-tooltip label="供应商">
        <template #default="{ row }">
          <span class="relative">
            {{ row.supplier_alias }}
            <el-tag
              v-if="row.activity_reject_count"
              class="tag-refuse"
              type="danger"
              effect="dark"
              size="mini"
            >
              驳回 {{ row.activity_reject_count }}
            </el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        show-overflow-tooltip
        label="收款人"
        prop="supplier_name"
      />
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="mobile"
        label="手机号"
      />
      <el-table-column
        align="center"
        show-overflow-tooltip
        label="已选细项"
        prop="details_count"
      />
      <el-table-column
        align="center"
        show-overflow-tooltip
        label="付款金额"
        prop="amount"
      />
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.page"
      :page-size="queryForm.list_row"
      :layout="layout"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog
      :visible.sync="refuseVisible"
      title="请输入驳回原因"
      width="500px"
    >
      <el-form>
        <el-form-item label="驳回原因">
          <el-input v-model="reason" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="refuseVisible = false">取 消</el-button>
          <el-button type="danger" @click="handleRefuse">确认驳回</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      title="查看验收材料"
      :visible.sync="checksVisible"
      width="1130px"
    >
      <div v-if="checks.length" class="checks">
        <el-image
          v-for="(check, index) in checks"
          :key="index"
          :src="checks[index]"
          :preview-src-list="checks"
          :z-index="5000"
          class="check"
          lazy
        />
      </div>
      <div v-else>没有提交验收材料</div>
    </el-dialog>

    <el-dialog
      v-if="uploadChecksVisible"
      title="上传材料"
      :visible.sync="uploadChecksVisible"
      width="800px"
      top="50px"
    >
      <el-form label-position="top">
        <el-form-item
          v-for="(type, typeIndex) in checkTypes"
          :key="type.id"
          :label="getUploadTypeLabel(type, typeIndex)"
        >
          <div class="checks-row">
            <div
              v-for="(file, fileIndex) in type.fileList"
              :key="file.uid"
              class="check-item"
              :style="{ backgroundImage: `url(${file.url})` }"
            >
              <div class="check-mask">
                <i
                  class="el-icon-delete check-delete"
                  @click="removeCheck(typeIndex, fileIndex)"
                ></i>
              </div>
            </div>
            <el-upload
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              multiple
              accept="image/*"
              :limit="6"
              :on-exceed="onChecksExceed"
              :on-change="
                (file, fileList) => onChecksChange(fileList, typeIndex)
              "
              :file-list="type.fileList"
              :show-file-list="false"
            >
              <i class="check-add el-icon-plus"></i>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item
          v-if="!checkTypes.length"
          label="该项目无需提交验收材料"
        />
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="uploadChecksVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSaveChecks">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getPendingList,
    getPendingDetailList,
    submitRequest,
    importFile
  } from '@/api/payment'
  import { sms, upload } from '@/api/common'
  import { getCheckTypes } from '@/api/activity'
  import { getStaticUserInfo } from '@/utils/user'
  // import { getChecks } from '@/api/invoice'
  import { uploadExpenseChecks as saveChecks, getExpenseChecks } from '@/api/activityExpenses'

  export default {
    name: 'PaymentPending',

    filters: {
      detailStatus: function (status) {
        const statusMap = {
          1: '待提交',
          2: '待审核',
          3: '财务提交总平台',
          4: '被驳回',
          5: '被驳回',
          6: '总审接收',
        }
        return statusMap[status] || '异常'
      },
    },

    data() {
      return {
        rate: 0,
        reject_count: 0,
        list: [],
        listLoading: false,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        queryForm: {
          page: 1,
          list_row: 10,
          keyword: '',
        },
        smsVisible: false,
        smsTimer: null,
        smsCountdown: 0,
        staticUserInfo: getStaticUserInfo(),
        refuseVisible: false,
        reason: '',
        details: [{}],
        checksVisible: false,
        checks: [],
        uploadChecksVisible: false,
        checkTypes: [],
        currentActivityId: null,
        currentRow: null,
      }
    },

    computed: {
      hasSelected() {
        return this.selectedRows.length > 0
      },
      totalAmount() {
        return this.selectedRows
          .map((row) => Number(row.subtotal))
          .reduce((sum, num) => sum + num, 0)
          .toFixed(2)
      },
      maskedPayPhone({ staticUserInfo }) {
        const { pay_phone_number: phone } = staticUserInfo
        return `${phone.slice(0, 3)}****${phone.slice(7)}`
      },
      selectedRows() {
        let rows = []
        this.list.forEach((item) => {
          rows = [...rows, ...item.selection]
        })
        return rows
      },
    },

    created() {
      this.getList()

    },

    activated() {
      this.getList()
    },

    methods: {
      toDecimal2(x) {
        var f = parseFloat(x);
        if (isNaN(f)) {
          return false;
        }
        var f = Math.round(x*100)/100;
        var s = f.toString();
        var rs = s.indexOf('.');
        if (rs < 0) {
          rs = s.length;
          s += '.';
        }
        while (s.length <= rs + 2) {
          s += '0';
        }
        return s;
      },
      importFile() {
        const idsStr = this.selectedRows.map((row) => row.id).join()
        importFile({id: idsStr}).then(res => {
          location.href = res
        })
      },
      async getList() {
        this.listLoading = true
        const { data, rate, reject_count } = await getPendingList(
          this.queryForm,
        )
        this.list = data.data.map((item) => ({
          ...item,
          children: [],
          details_count: 0,
          amount: 0,
          selection: [],
        }))
        console.log(3333,this.list)
        this.total = data.total
        this.rate = +rate
        this.reject_count = reject_count
        this.listLoading = false
      },
      handleSizeChange(val) {
        this.queryForm.list_row = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.queryForm.page = val
        this.getList()
      },
      search() {
        this.queryForm.page = 1
        this.getList()
      },
      handleSelectionChange(index, rows) {
        this.list[index].selection = rows
        this.list[index].details_count = rows.length
        this.list[index].amount = rows.reduce(
          (result, item) => result + Number(item.subtotal),
          0,
        )
        this.$forceUpdate()
      },
      submit() {
        this.$confirm('确定提交付款申请?', { type: 'warning' }).then(() => {
          const idsStr = this.selectedRows.map((row) => row.id).join()
          submitRequest({ id: idsStr }).then((res) => {
            this.$baseMessage(res, 'success')
            this.getList()
          })
        })
      },
      async sendSms() {
        await sms()
        this.smsCountdown = 60
        this.smsTimer = setInterval(() => {
          this.smsCountdown--
          if (this.smsCountdown === 0) {
            clearInterval(this.smsTimer)
          }
        }, 1000)
      },
      handleRefuse() {
        this.refuseVisible = false
      },
      showChecks(row) {
        getExpenseChecks({ id: row.id }).then((res) => {
          this.checks = res
          this.checksVisible = true
        })
      },
      showReason({ reject_msg }) {
        this.$alert(reject_msg, '驳回原因')
      },
      async handleExpandChange(row) {
        const supplierId = row.id
        const { data } = await getPendingDetailList({
          supplier_id: supplierId,
          page: 1,
          list_row: 99999,
        })
        row.children = data.map((item) => ({
          ...item,
          // is_check 字段: 1-可以点击, 2-不能点击, 需要上传材料
          has_checks: item.is_check === 1 && item.is_supplier_check === 1,
        }))
      },
      isSelectable(row) {
        console.log(23,row)
        return row.has_checks
      },
      showUploadChecks(id, row) {
        this.currentActivityId = id
        this.currentRow = row
        const types = [{
          project_category: '上传材料',
          fileList: [],
        }]
        // types.unshift({ id: 0, project_category: '未分配', fileList: [] })
        this.checkTypes = types
        this.uploadChecksVisible = true
      },
      getUploadTypeLabel(type, index) {
        let label = type.project_category
        const num = type.fileList.length
        // label += ` ${index ? `(${num}/6)` : num}`
        label += ` (${num}/6)`
        return label
      },
      onChecksExceed() {
        this.$baseMessage('最多只能上传 6 张图片哦', 'warning')
      },
      handleSaveChecks() {
        if (!this.validateChecks()) return
        const types = this.checkTypes
        let typeImages
        types.forEach((type) => {
          const files = type.fileList
          typeImages = files.map((file) => file.url).join(',')
        })
        saveChecks({
          id: this.currentActivityId,
          check_img: typeImages,
        }).then((res) => {
          this.uploadChecksVisible = false
          this.$baseMessage(res, 'success')
          this.handleExpandChange(this.currentRow)
        })
      },
      onChecksChange(fileList, index) {
        // 注: fileList 包含全部图片
        const type = this.checkTypes[index]
        // 处理待上传图片
        const formData = new FormData()
        fileList
          .filter((file) => file.raw)
          .forEach((file) => formData.append('file[]', file.raw))
        // 上传图片
        upload(formData).then((res) => {
          // 上传后处理
          const urls = res.url
          type.fileList = [
            ...fileList.filter((file) => !file.raw),
            ...urls.map((url) => ({ url })),
          ]
          this.$set(this.checkTypes, index, type)
        })
      },
      validateChecks() {
        const types = this.checkTypes
        for (const type of types) {
          const files = type.fileList
          for (const file of files) {
            if (file.url.startsWith('blob:')) {
              this.$baseMessage('图片上传中，请重试', 'error')
              return false
            }
          }
        }
        return true
      },
      removeCheck(typeIndex, fileIndex) {
        this.checkTypes[typeIndex].fileList.splice(fileIndex, 1)
        this.$forceUpdate()
      },
    },
  }
</script>

<style lang="scss">
.el-upload--picture-card{
  position: relative;
  width: 100px;
  height: 100px;
}

.el-table__expand-icon > .el-icon{
  margin-top: -10px!important;
}
.el-table__expand-icon > .el-icon-arrow-right{
  font-size: 20px!important;
  line-height: 20px;
}
.el-table__expand-icon{
  -webkit-transform: rotate(0deg);
  transform: rotate(0deg);
}

.el-table__expand-icon
.el-icon-arrow-right:before{
  content: "\e7a0";
  color: #1890ff;
}
.el-table__expand-icon--expanded
.el-icon-arrow-right:before{
  content: "\e7a2";
  color: #1890ff;
}
/*.el-table__expand-icon--expanded
.el-icon-arrow-right:before{
  content: "\e6d8";
  color: #1890ff;
}*/
  ::v-deep .vab-query-form .left-panel {
    flex-wrap: nowrap;
  }

  ::v-deep .vab-query-form .left-panel > .el-button {
    margin-right: 15px !important;
    margin-bottom: 0 !important;
    margin-left: 0 !important;
  }

  .summary-item {
    display: flex;
    align-items: center;
    white-space: nowrap;
  }

  .summary-item:not(:last-child) {
    margin-right: 20px;
  }

  .summary-value {
    margin-right: 4px;
    font-size: 18px;
    font-weight: bold;
    color: #000;
  }

  .summary-item-danger,
  .summary-item-danger .summary-value {
    color: #f56c6c;
  }

  .right-panel .summary-item {
    margin-top: -10px;
  }

  .right-panel .summary-item:last-child {
    margin-right: 10px !important;
  }

  .search-input {
    width: 255px;
  }

  ::v-deep .phone-code button.el-button {
    display: block;
    width: 92px;
    height: 32px;
    color: #fff;
    background: #1890ff;
    border-color: #1890ff;
    border-radius: 0;
  }

  ::v-deep .phone-code button.el-button[disabled] {
    height: 30px;
    color: #c0c4cc;
    background: #ebeef5;
    border-color: #ebeef5;
  }

  .details-meta {
    margin-bottom: 20px;
  }

  .details-meta-label {
    display: inline-block;
    width: 6em;
    font-weight: bold;
  }

  .details-meta-item:not(:first-child) {
    margin-top: 10px;
  }

  .checks {
    display: flex;
    flex-wrap: wrap;
    margin-right: -10px;
    margin-bottom: -10px;
  }

  .check {
    width: 100px;
    height: 100px;
    margin-right: 10px;
    margin-bottom: 10px;
  }

  .relative {
    position: relative;
  }

  .tag-refuse {
    position: absolute;
    top: 50%;
    right: 0;
    border-radius: 999px;
    transform: translate(calc(100% + 7px), -50%);
  }

  .subtable {
    margin-top: -8.5px !important;
    margin-bottom: -7.5px !important;
  }

  .status-reject {
    color: #f56c6c;
    cursor: pointer;
    border-bottom: 1px dashed #dcdfe6;
  }

  .sub-btn {
    padding: 0 !important;
  }

  .sub-btn-danger {
    color: #f56c6c;
  }

  .checks-row {
    display: flex;
    align-items: center;
  }

  .check-item {
    position: relative;
    box-sizing: border-box;
    width: 100px;
    height: 100px;
    margin-right: 10px;
    background-position: center;
    background-size: cover;
    border: 1px solid #c0ccda;
    border-radius: 7px;
  }

  .check-mask {
    position: absolute;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    opacity: 0;
    transition: 0.3s;
  }

  .check-item:hover .check-mask {
    opacity: 1;
  }

  .check-delete {
    position: absolute;
    top: 50%;
    left: 50%;
    font-size: 20px;
    color: #fff;
    cursor: pointer;
    transform: translate(-50%, -50%);
  }

  ::v-deep .el-upload--picture-card {
    position: relative;
    width: 100px;
    height: 100px;
  }

  .check-add {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
</style>

<style>
  html body .el-table.subtable th,
  html body[class*='vab-theme-'] .el-table.subtable th {
    background: #fff;
  }

  .el-table--border.subtable td:first-child .cell {
    padding-left: 14px !important;
  }

  html body .el-table.subtable td .cell,
  html body .el-table.subtable th .cell,
  html body[class*='vab-theme-'] .el-table.subtable td .cell,
  html body[class*='vab-theme-'] .el-table.subtable th .cell {
    font-size: 12px;
  }
</style>
